import { AppResult } from '@/types/base-type';
import { request } from '@/utils/util';
import { Menu, Role } from '@/types/sys-type';
import { Storage } from '@/utils/storage';

const AccessTokenConstant = {
  id: 'id',
  name: 'token',
  access: 'access',
  refresh: 'refresh',
  remark: 'remark',
};

const loginStorage = new Storage('session', 'login_');

async function login(params?: any): Promise<AppResult<string>> {
  return request('/authenticate', {
    method: 'post',
    data: params,
  });
}

interface CurrentUser {
  username?: string;
  nickname?: string;
  roles?: Role[];
  resources?: Menu[];
}

async function getCurrentUser(): Promise<AppResult<CurrentUser>> {
  return request('/getCurrentUser', {
    method: 'get',
    params: {},
  });
}

async function logout(): Promise<AppResult<any>> {
  loginStorage.clear();
  return request('/logout', {
    method: 'get',
    params: {},
  });
}

const isLogin = () => {
  return loginStorage.get(AccessTokenConstant.name || 'token') !== null;
};

export { login, getCurrentUser, logout, isLogin, CurrentUser, AccessTokenConstant, loginStorage };
